package com.test.work.common.datasource;

import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @author jiangxia
 * @date 2021年12月09日 11:25
 */
@Configuration
@MapperScan(basePackages = "com.test.work.datahandler.mapper.db2",sqlSessionFactoryRef = "db2SqlSessionFactory")
public class DB2DataSourceConfig {
    static final String MAPPER_LOCATION = "classpath*:/mapper/db2/*.xml";

    @Bean("db2DataSource")
    @ConfigurationProperties(prefix = "spring.datasource.dynamic.datasource.db2")
    public DataSource getDb1DataSource(){
        return DataSourceBuilder.create().build();
    }

    @Bean("db2SqlSessionFactory")
    public SqlSessionFactory db2SqlSessionFactory(@Qualifier("db2DataSource") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean factoryBean = new MybatisSqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPER_LOCATION));
        //驼峰命名
        factoryBean.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);
        //輸出日志
        factoryBean.getObject().getConfiguration().setLogImpl(org.apache.ibatis.logging.stdout.StdOutImpl.class);
        return factoryBean.getObject();
    }


    @Bean(name = "mysql2TransactionManager")
    public DataSourceTransactionManager transactionManager(@Qualifier("db2DataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean("db2SqlSessionTemplate")
    public SqlSessionTemplate db2SqlSessionTemplate(@Qualifier("db2SqlSessionFactory") SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
